package nic.controller;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Properties;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.lang.ArrayUtils;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.lexer.Page;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.SimpleNodeIterator;
import org.htmlparser.visitors.NodeVisitor;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import au.com.bytecode.opencsv.CSVReader;

public class QNapController {

	private final String csvPath = "/cgi-bin/Qdownload/html/";
	private final String btOptionCmd = "/cgi-bin/Qdownload/btoption.cgi?";
	private final String upParam = "name=up";
	private final String downParam = "name=down";
	private final String pauseParam = "name=pause";
	private final String indexParamKey = "index";
	private final String restartParam = "name=restart";
	private final String kindParamKey = "kind";
	private final String showErrorParam = "name=show_error";
	private final String pageParamKey = "page";
	private final String jobIndexParamKey = "jobindex";
	//private final String addTorrentParam = "name=add";
//	private final String deleteFileParamKey = "delete_file";
//	private final String deleteSubmitParam = "name=del_submit";
	private final String submitTorrentParam = "name=add_submit";
	private final String getConfigurationParam = "name=set";
	private final String configurationSubmitParam = "name=set_submit";
	private final String shareTimeParam = "name=edit";
	private final String shareTimeSubmitParam = "name=edit_submit";
	private final String addFtpParam = "name=add_qget";
	private final String addFtpSubmitParam = "name=add_qget_submit";
	private String username = "";
	private String password = "";
	private String serverAddress = "";
	private int port = -1;
	private Transliteration rot13;
	
	private final String listUrl
		= "/cgi-bin/Qdownload/Get_DL_List.cgi?status="; 
			
	public enum TorrentDownloadState { Running, Paused, Finished };
	
	public QNapController()
	{
		Authenticator.setDefault(new QNapAuthenticator());
		this.rot13 = Transliteration.compile("n-za-mN-ZA-M", "a-zA-Z");
		
		try {
			// Try to get the login credentials from a file
			FileInputStream in = new FileInputStream("my.properties");
			Properties props = new Properties();
			props.load(in);
			
			if (props.containsKey("jnappwd"))
			{
				this.password = decrypt((String)props.get("jnappwd"));
			}
			if (props.containsKey("jnapusr"))
			{
				this.username = decrypt((String)props.get("jnapusr"));
			}
			if (props.containsKey("jnapsrv"))
			{
				this.serverAddress = decrypt((String)props.get("jnapsrv"));
			}
			if (props.containsKey("jnapprt"))
			{
				this.port = Integer.parseInt(decrypt((String)props.get("jnapprt")));
			}
		} catch (IOException e) {
		
		}
	}
	
	public String getServerAddress() {
		return serverAddress;
	}
	
	public String getUsername() {
		return username;
	}
	
	public String getPassword() {
		return password;
	}
	
	public int getPort() {
		return port;
	}
	
	public void setDefaultPort(int port) {
		this.port = port;
	}
	
	public void moveTaskUp(int taskIndex)
	{
		String cmd = btOptionCmd + upParam
			+ "&" + indexParamKey + "=" + taskIndex;
		getQNapUrlContent(cmd);
		//System.out.println(content);
	}
	
	public void restartTask(int taskIndex, 
			TorrentDownloadState kind)
	{	
		String cmd = btOptionCmd + restartParam
		+ "&" + indexParamKey + "=" + taskIndex + "&"
		+ kindParamKey + "=" + stateToString(kind);
		getQNapUrlContent(cmd);
		//System.out.println(content);
	}
	
	public String getTaskDownloadInfo(int taskIndex, 
			TorrentDownloadState page)
	{	
		String cmd = btOptionCmd + showErrorParam
		+ "&" + jobIndexParamKey + "=" + taskIndex + "&"
		+ pageParamKey + "=" + stateToString(page);
		String content = getQNapUrlContent(cmd);
	
		TaskDownloadInfoNodeVisitor visitor 
			= new TaskDownloadInfoNodeVisitor();

		Parser parser = new Parser(
			new Lexer(new Page(content,"UTF-8")));
		try {
			parser.visitAllNodesWith(visitor);
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		return visitor.info;
	}
	
	public void deleteTask(int taskIndex, TorrentDownloadState page,
			boolean deleteFiles)
	{
		String cmd = "/cgi-bin/Qdownload/DL_Task_Option.cgi?status=" + stateToString(page)
			+ "&todo=delete&task_index=" + taskIndex + "&delete_file="; 
		
		if (deleteFiles)
		{
			cmd += "1";
		} else
		{
			cmd += "0";
		}
				
		getQNapUrlContent(cmd);
	}
	
	public void setConfiguration(int maxConcurrentDownloads, int maxDownloadRate,
			int maxUploadRate, int btPortRangeStart, int btPortStartEnd, boolean natPortForwarding)
	{
		Hashtable<String, String> attributes = new Hashtable<String, String>();
		attributes.put("JobNum", Integer.toString(maxConcurrentDownloads));
		attributes.put("maxDownRate", Integer.toString(maxDownloadRate));
		attributes.put("maxUpRate", Integer.toString(maxUploadRate));
		attributes.put("portFrom", Integer.toString(btPortRangeStart));
		attributes.put("portTo", Integer.toString(btPortStartEnd));
		if (natPortForwarding)
		{
			attributes.put("upnpPortForward", "checked");
		}
		
		String cmd = btOptionCmd + configurationSubmitParam;
		
		getQNapUrlContent(cmd, attributes);
	}
	
	public GetConfigurationNodeVisitor getConfiguration()
	{	
		String cmd = btOptionCmd + getConfigurationParam;
		String content = getQNapUrlContent(cmd);
		GetConfigurationNodeVisitor visitor 
			= new GetConfigurationNodeVisitor();

		Parser parser = new Parser(
			new Lexer(new Page(content,"UTF-8")));
		try {
			parser.visitAllNodesWith(visitor);
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return visitor;
	}
	
	public int getShareTime(int taskIndex, TorrentDownloadState page)
	{
		String cmd = btOptionCmd + shareTimeParam
			+ "&" + jobIndexParamKey + "=" + taskIndex + "&"
			+ pageParamKey + "=" + stateToString(page);
		String content = getQNapUrlContent(cmd);
		GetShareTimeNodeVisitor visitor 
			= new GetShareTimeNodeVisitor();

		Parser parser = new Parser(
			new Lexer(new Page(content,"UTF-8")));
		try {
			parser.visitAllNodesWith(visitor);
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return visitor.getShareTime();
	}
	
	public Vector<NetworkShare> getNetworkShares()
	{
		String cmd = btOptionCmd + addFtpParam;
		
		String content = getQNapUrlContent(cmd);
		GetNetworkSharesVisitor visitor = new GetNetworkSharesVisitor();

		Parser parser = new Parser(
			new Lexer(new Page(content,"UTF-8")));
		try {
			parser.visitAllNodesWith(visitor);
			boolean noneIsSelected = true;	
			for (NetworkShare networkShare : visitor.networkShares)
			{
				if (networkShare.isSelected)
				{
					noneIsSelected = false;
					break;
				}
			}
			if (noneIsSelected)
			{
				// Search for the QDownload folder
				for (NetworkShare networkShare : visitor.networkShares)
				{
					if (networkShare.text.equalsIgnoreCase("qdownload"))
					{
						networkShare.isSelected = true;
						break;
					}
				}
			}
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return visitor.networkShares;
	}
	
	public void setShareTime(int taskIndex, TorrentDownloadState page, int shareTime) {
		
		Hashtable<String, String> attributes = new Hashtable<String, String>();
		attributes.put(pageParamKey, stateToString(page));
		attributes.put(jobIndexParamKey, Integer.toString(taskIndex));
		attributes.put("time", Integer.toString(shareTime));
		
		String cmd = btOptionCmd + shareTimeSubmitParam;
		
		getQNapUrlContent(cmd, attributes);
	}
	
	private String stateToString(TorrentDownloadState type)
	{
		switch (type)
		{
		case Paused:
			return "pause";
		case Finished:
			return "finish";
		case Running:
			return "run";
		default:
			return null;
		}
	}
	
	public void pauseTask(int taskIndex)
	{
		String cmd = btOptionCmd + pauseParam
			+ "&" + indexParamKey + "=" + taskIndex;
		getQNapUrlContent(cmd);
		//System.out.println(content);
	}
	
	public void moveTaskTo(int oldPos, int newPos)
	{
		while (oldPos < newPos)
		{
			moveTaskDown(oldPos);
			oldPos++;
		}
		while (oldPos > newPos) {
			moveTaskUp(oldPos);
			oldPos--;
		}
	}
	
	public void moveTaskDown(int taskIndex)
	{
		String cmd = btOptionCmd + downParam
			+ "&" + indexParamKey + "=" + taskIndex;
		getQNapUrlContent(cmd);
		//System.out.println(content);
	}
	
	public void addTorrent(File torrent)
	{
		try {
	        FilePart torrentFilePart = new FilePart(torrent.getName(), torrent);
	        PostMethod post = new PostMethod(
	        		getQNapUrl(btOptionCmd + submitTorrentParam).toString());
	        //torrentFilePart.setTransferEncoding("ISO-8859-1");
	        torrentFilePart.setContentType("application/x-bittorrent");
	        Part[] parts = { torrentFilePart };
	        //client.setConnectionTimeout(8000);
	        post.setRequestEntity(
	        		new MultipartRequestEntity(parts, post.getParams()));
	        HttpClient client = new HttpClient();
	        client.getParams().setAuthenticationPreemptive(true);
	        Credentials defaultcreds = new UsernamePasswordCredentials(
	        		getUsername(), getPassword());
	        client.getState().setCredentials(new AuthScope(getServerAddress(),
	        		getPort(), AuthScope.ANY_REALM), defaultcreds);
	        client.executeMethod(post);
//	        BufferedReader reader = new BufferedReader(
//					new InputStreamReader(post.getResponseBodyAsStream()));
//	        String str;
//	        while (reader != null && (str = reader.readLine()) != null)
//	        {
//	        	System.out.println(str);
//	        }
	        post.releaseConnection();			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Vector<String[]> getList(TorrentDownloadState state) {
		Vector<String[]> list = new Vector<String[]>();
		try
		{
			// Parse the csv
	        CSVReader reader = new CSVReader(
	        		getQNapUrlContentReader(listUrl + stateToString(state)));
	        String[] nextLine;
	
			while ((nextLine = reader.readNext()) != null) {
				if (nextLine.length > 0 && "".equals(nextLine[0]) == false)
				{
					if (state == TorrentDownloadState.Running)
					{
						try
						{
						double sizeMb = Double.parseDouble(nextLine[2]);
						double downloadRateKbS = Double.parseDouble(nextLine[3]);
						double donePercent = Double.parseDouble(nextLine[4]);
						int remainingSeconds = (int)(1000 * (sizeMb * (100 - donePercent) / 100) / downloadRateKbS);
						int remainingMinutes = remainingSeconds / 60;
						int remainingHours = remainingMinutes / 60;
						String str = String.format("%02d", remainingHours) + ":" + String.format("%02d", remainingMinutes % 60) + ":" + String.format("%02d", remainingSeconds % 60);
	//					Date date = new Date(remainingSeconds * 1000);
	//					SimpleDateFormat sdf = new SimpleDateFormat(
	//			    			"d:HH:mm:ss", Locale.US);
						nextLine = (String[]) ArrayUtils.add(
								nextLine, str/*sdf.format(date)*/);
						} catch (Exception e)
						{}
					}
					list.add(nextLine);
				}
			}
		
		} catch (IOException e) {
			e.printStackTrace();
		}
		// Remove the first line which is empty
		return list;
	}

	private Vector<String[]> getQNapList(String cmd) {
		String content = getQNapUrlContent(cmd);
        
        try {
	        String csvFilename = getCsvFilename(content);
	        
	        // Parse the csv
	        CSVReader reader = new CSVReader(
	        		getQNapUrlContentReader(csvPath + csvFilename));
	        String[] nextLine;
	        Vector<String[]> list = new Vector<String[]>();

			while ((nextLine = reader.readNext()) != null) {
				if ("".equals(nextLine) == false)
				{
					list.add(nextLine);
				}
			}
			return list;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	private URL getQNapUrl(String cmd) {
		try {
			return new URL("http", getServerAddress(), getPort(), cmd);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	private BufferedReader getQNapUrlContentReader(String cmd)
	{
		URL url = getQNapUrl(cmd);
        InputStream ins;
		try {
			ins = url.openConnection().getInputStream();
			return new BufferedReader(new InputStreamReader(ins));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return null;
	}
	
	private String getQNapUrlContent(String cmd)
	{
		try {	
			BufferedReader reader = getQNapUrlContentReader(cmd);
	       
	        String str;
	        String content = "";
	        while(reader != null && (str = reader.readLine()) != null)
	        {
	            content += str;
	        }
	        return content;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		return null;
	}
	
	private String getQNapUrlContent(String cmd, 
			Hashtable<String, String> postData)
	{
		String stringData = "";
		Enumeration<String> keys = postData.keys();
		int i = 0;
		try {
		while (keys.hasMoreElements())
		{
			if (i > 0)
			{
				stringData += "&";
			}
			String key = URLEncoder.encode(keys.nextElement(), "UTF-8");
			String value = URLEncoder.encode(postData.get(key), "UTF-8");
			
			stringData += key + "=" + value;
			
			i++;
		}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return getQNapUrlContent(cmd, stringData);
	}
	
	private String getQNapUrlContent(String cmd, String postData)
	{
		try {	
			URL url = getQNapUrl(cmd);
	        URLConnection conn = url.openConnection();
	        
	        conn.setDoOutput(true);
	        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
	        wr.write(postData);
	        wr.flush();
	        
	        InputStream ins = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
	       
	        String str;
	        String content = "";
	        while((str = reader.readLine()) != null)
	        {
	            content += str;
	        }
	        return content;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}

	class QNapAuthenticator extends Authenticator {

		public QNapAuthenticator()
		{
		}
		
        public PasswordAuthentication getPasswordAuthentication () {
            return new PasswordAuthentication (QNapController.this.getUsername(),
            		QNapController.this.getPassword().toCharArray());
        }
    }
	
	private String getCsvFilename(String content)
		throws ParserException
	{	
		QNapRefreshNodeVisitor visitor 
			= new QNapRefreshNodeVisitor();

		Parser parser = new Parser(
				new Lexer(new Page(content,"UTF-8")));
		parser.visitAllNodesWith(visitor);
		return visitor.csvFilename;
	}
	
	public void addFtp(String url, NetworkShare saveFolder,
			boolean useCredentials, String username, String password)
	{
		try {
			Hashtable<String, String> attributes = new Hashtable<String, String>();
			attributes.put("url", URLEncoder.encode(url, "UTF-8"));
			attributes.put("saveto", URLEncoder.encode(saveFolder.value, "UTF-8"));
			if (useCredentials)
			{
				attributes.put("ID_PWD", "ON");
			}
			attributes.put("user", username);
			attributes.put("pwd", password);
			
			String cmd = btOptionCmd + addFtpSubmitParam;
			
			getQNapUrlContent(cmd, attributes);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	class QNapRefreshNodeVisitor extends NodeVisitor
	{
		String csvFilename = null;
		
		@Override
		public void visitTag(Tag tag) {
			String name = tag.getTagName();

			if ("a".equalsIgnoreCase(name)
					&& tag.getAttribute("ID").equals("filename"))
			{
				csvFilename = tag.getChildren().elementAt(0).getText();
			}
		}
	}
	
	class TaskDownloadInfoNodeVisitor extends NodeVisitor
	{
		String info = null;
		
		@Override
		public void visitTag(Tag tag) {
			String name = tag.getTagName();

			if ("td".equalsIgnoreCase(name)
					&& tag.getChildren().size() == 1
					&& tag.getChildren().elementAt(0) instanceof TextNode)
			{
				info = tag.getChildren().elementAt(0).getText();
			}
		}
	}
	
	public class GetConfigurationNodeVisitor extends NodeVisitor
	{
		int maxConcurrentDownloads;
		int maxDownloadRate;
		int maxUploadRate;
		int btPortRangeStart;
		int btPortStartEnd;
		boolean natPortForwarding;
		
		@Override
		public void visitTag(Tag tag) {
			String name = tag.getTagName();

			if ("td".equalsIgnoreCase(name))
			{
				SimpleNodeIterator it = tag.getChildren().elements();
				while (it.hasMoreNodes())
				{
					Node node = it.nextNode();
					
					if (node instanceof TagNode
							&& "input".equalsIgnoreCase(((TagNode)node).getTagName()))
					{
						TagNode tagNode = (TagNode)node;
						String id = tagNode.getAttribute("name");
						if (id.equals("JobNum"))
						{
							maxConcurrentDownloads = Integer.parseInt(tagNode.getAttribute("value"));
						} else if (id.equals("maxDownRate"))
						{
							maxDownloadRate = Integer.parseInt(tagNode.getAttribute("value"));
						} else if (id.equals("maxUpRate"))
						{
							maxUploadRate = Integer.parseInt(tagNode.getAttribute("value"));
						} else if (id.equals("portFrom"))
						{
							btPortRangeStart = Integer.parseInt(tagNode.getAttribute("value"));
						} else if (id.equals("portTo"))
						{
							btPortStartEnd = Integer.parseInt(tagNode.getAttribute("value"));
						} else if (id.equals("upnpPortForward"))
						{
							natPortForwarding = tagNode.getAttribute("checked") != null;
						}
					}
				}
			}
		}

		public int getBtPortRangeStart() {
			return btPortRangeStart;
		}

		public int getBtPortStartEnd() {
			return btPortStartEnd;
		}

		public int getMaxConcurrentDownloads() {
			return maxConcurrentDownloads;
		}

		public int getMaxDownloadRate() {
			return maxDownloadRate;
		}

		public int getMaxUploadRate() {
			return maxUploadRate;
		}

		public boolean isNatPortForwarding() {
			return natPortForwarding;
		}
	}
	
	public class GetShareTimeNodeVisitor extends NodeVisitor
	{
		int shareTime;
		
		@Override
		public void visitTag(Tag tag) {
			String name = tag.getTagName();

			if ("td".equalsIgnoreCase(name))
			{
				SimpleNodeIterator it = tag.getChildren().elements();
				while (it.hasMoreNodes())
				{
					Node node = it.nextNode();
					
					if (node instanceof TagNode
							&& "input".equalsIgnoreCase(((TagNode)node).getTagName()))
					{
						TagNode tagNode = (TagNode)node;
						String id = tagNode.getAttribute("name");
						if (id.equals("time"))
						{
							shareTime = Integer.parseInt(tagNode.getAttribute("value"));
						}
					}
				}
			}
		}

		public int getShareTime() {
			return shareTime;
		}
	}
	
	private class GetNetworkSharesVisitor extends NodeVisitor
	{
		Vector<NetworkShare> networkShares = new Vector<NetworkShare>();
		
		@Override
		public void visitTag(Tag tag) {
			String name = tag.getTagName();

			if ("td".equalsIgnoreCase(name))
			{
				SimpleNodeIterator it = tag.getChildren().elements();
				while (it.hasMoreNodes())
				{
					Node node = it.nextNode();
					
					if (node instanceof TagNode
							&& "select".equalsIgnoreCase(((TagNode)node).getTagName()))
					{
						TagNode tagNode = (TagNode)node;
						SimpleNodeIterator it2 = tagNode.getChildren().elements();
						while (it2.hasMoreNodes())
						{
							Node node2 = it2.nextNode();
							if (node2 instanceof TagNode
									&& "option".equalsIgnoreCase(((TagNode)node2).getTagName()))
							{
								TagNode optionTagNode = (TagNode)node2;
								
								String value = optionTagNode.getAttribute("value");
								String text = optionTagNode.getChildren().elementAt(0).getText();
								boolean isSelected = optionTagNode.getAttribute("SELECTED") != null;
								networkShares.add(new NetworkShare(text, value, isSelected));
							}
						}
					}
				}
			}
		}
	}
	
	public class NetworkShare
	{
		private String text;
		private String value;
		private boolean isSelected;
		
		public NetworkShare(String text, String value, boolean isSelected) {
			super();
			this.text = text;
			this.value = value;
			this.isSelected = isSelected;
		}

		public boolean isSelected() {
			return isSelected;
		}

		public String getText() {
			return text;
		}

		public String getValue() {
			return value;
		}
		
		@Override
		public String toString() 
		{
			return getText();
		}
	}

	public void setServer(String serverAddress,
			String username, String password, int port) {
		this.serverAddress = serverAddress;
		this.username = username;
		this.password = password;
		this.port = port;
	}
	
	public boolean checkServer(String serverAddress,
			String username, String password, int port)
	{
		if (serverAddress == null || username == null || password == null
				|| port < 0)
		{
			return false;
		}
		String cmd = "/cgi-bin/Qdownload/qdownloadindex.cgi";
		String oldUsername = getUsername();
		String oldPassword = getPassword();
		String oldServerAddress = getServerAddress();
		int oldPort = getPort();

//		try {
			
			setServer(serverAddress, username, password, port);
			
			String content = getQNapUrlContent(cmd);

			boolean success = content.contains("DOCTYPE HTML PUBLIC");
			
//			ByteArrayInputStream ins = new ByteArrayInputStream(content.trim().getBytes("UTF-8"));
//			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//			DocumentBuilder db = dbf.newDocumentBuilder();
//
//			Document doc = db.parse(ins);
//
//			boolean success = false;
//			for (int i = 0; i < doc.getDocumentElement().getChildNodes().getLength(); i++)
//			{
//				org.w3c.dom.Node node
//					= doc.getDocumentElement().getChildNodes().item(i);
//				if (node.getNodeName() == "Result")
//				{
//					success = node.getChildNodes().item(0)
//						.getTextContent().equals("success");
//					break;
//				}
//			}
			
//			setServer(oldServerAddress, oldUsername, oldPassword);
			
//			return success;
//		} catch (java.net.ProtocolException e)
//		{
//			return false; // wrong username or password
//		} catch (IOException e) {
//			e.printStackTrace();
//		} catch (ParserConfigurationException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (SAXException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		if (success == false)
		{
			setServer(oldServerAddress, oldUsername, oldPassword, oldPort);
		}

		
		return success;
	}
	
	public void saveCredentials()
	{
		FileOutputStream out;
		try {
			out = new FileOutputStream("my.properties");
		
	        Properties props = new Properties();
	        props.put("jnapusr", encrypt(getUsername()));
	        props.put("jnappwd", encrypt(getPassword()));
	        props.put("jnapsrv", encrypt(getServerAddress()));
	        props.put("jnapprt", encrypt(Integer.toString(getPort())));
	        props.store(out, "properties");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean checkServer() {
		return checkServer(getServerAddress(), getUsername(),
				getPassword(), getPort());
	}
	
	private String encrypt(String str)
	{
		return this.rot13.translate(str);
	}
	
	private String decrypt(String str)
	{
		return this.rot13.translate(str);
	}
}
